/**
 * 测试环境设置文件
 * 创建时间：2025-09-11
 * 作者：开发团队
 * 目的：配置测试环境，mock全局依赖
 */

import { vi } from 'vitest'
import { config } from '@vue/test-utils'

// Mock Element Plus 组件
vi.mock('element-plus', () => {
  const createMockComponent = (name: string) => ({
    name,
    template: `<div class="${name.toLowerCase()}"><slot /></div>`,
    props: ['modelValue', 'loading', 'disabled', 'placeholder', 'type', 'size', 'data', 'columns', 'stripe', 'label', 'prop', 'width', 'title', 'visible', 'span', 'gutter', 'currentPage', 'pageSize', 'total', 'layout', 'pageSizes', 'icon', 'description', 'value', 'suffix', 'clearable', 'showPassword', 'showWordLimit', 'maxlength', 'rows', 'border', 'divided', 'command', 'round', 'text'],
    emits: ['update:modelValue', 'click', 'change', 'clear', 'keyup', 'command', 'size-change', 'current-change', 'close'],
    setup(props: Record<string, unknown>, { emit }: { emit: (event: string, ...args: unknown[]) => void }) {
      return {
        handleClick: () => emit('click'),
        handleChange: (value: unknown) => emit('update:modelValue', value),
        handleCommand: (command: string) => emit('command', command)
      }
    }
  })

  return {
    ElMessage: vi.fn((options) => {
      console.log('ElMessage called:', options)
    }),
    ElMessageBox: {
      confirm: vi.fn(() => Promise.resolve())
    },
    ElButton: createMockComponent('ElButton'),
    ElInput: createMockComponent('ElInput'),
    ElForm: createMockComponent('ElForm'),
    ElFormItem: createMockComponent('ElFormItem'),
    ElCard: createMockComponent('ElCard'),
    ElTable: createMockComponent('ElTable'),
    ElTableColumn: createMockComponent('ElTableColumn'),
    ElDialog: createMockComponent('ElDialog'),
    ElSelect: createMockComponent('ElSelect'),
    ElOption: createMockComponent('ElOption'),
    ElPagination: createMockComponent('ElPagination'),
    ElTag: createMockComponent('ElTag'),
    ElStatistic: createMockComponent('ElStatistic'),
    ElDescriptions: createMockComponent('ElDescriptions'),
    ElDescriptionsItem: createMockComponent('ElDescriptionsItem'),
    ElResult: createMockComponent('ElResult'),
    ElAlert: createMockComponent('ElAlert'),
    ElEmpty: createMockComponent('ElEmpty'),
    ElRow: createMockComponent('ElRow'),
    ElCol: createMockComponent('ElCol'),
    ElIcon: createMockComponent('ElIcon')
  }
})

// Mock Element Plus Icons
vi.mock('@element-plus/icons-vue', () => ({
  Refresh: { name: 'Refresh' },
  Search: { name: 'Search' },
  View: { name: 'View' },
  Camera: { name: 'Camera' },
  SuccessFilled: { name: 'SuccessFilled' },
  CircleCloseFilled: { name: 'CircleCloseFilled' }
}))

// Mock 样式文件
vi.mock('*.scss', () => ({}))
vi.mock('*.css', () => ({}))

// Mock Vue Router
vi.mock('vue-router', async () => {
  const actual = await vi.importActual('vue-router')
  return {
    ...actual,
    createRouter: vi.fn(() => ({
      push: vi.fn(),
      replace: vi.fn(),
      go: vi.fn(),
      back: vi.fn(),
      forward: vi.fn(),
      beforeEach: vi.fn()
    })),
    createWebHistory: vi.fn(),
    useRouter: () => ({
      push: vi.fn(),
      replace: vi.fn(),
      go: vi.fn(),
      back: vi.fn(),
      forward: vi.fn()
    }),
    useRoute: () => ({
      path: '/',
      name: 'home',
      params: {},
      query: {},
      meta: {}
    })
  }
})

// Mock axios
vi.mock('axios', () => ({
  default: {
    create: vi.fn(() => ({
      get: vi.fn(() => Promise.resolve({ data: {} })),
      post: vi.fn(() => Promise.resolve({ data: {} })),
      put: vi.fn(() => Promise.resolve({ data: {} })),
      delete: vi.fn(() => Promise.resolve({ data: {} })),
      interceptors: {
        request: {
          use: vi.fn()
        },
        response: {
          use: vi.fn()
        }
      }
    }))
  },
  AxiosError: class AxiosError extends Error {
    constructor(message: string) {
      super(message)
      this.name = 'AxiosError'
    }
  }
}))

// 全局测试工具配置
config.global.mocks = {
  $t: (msg: string) => msg, // Mock i18n
}

// Mock window 对象方法
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation((query) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(), // deprecated
    removeListener: vi.fn(), // deprecated
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
  })),
})

// Mock localStorage
const localStorageMock = {
  getItem: vi.fn(),
  setItem: vi.fn(),
  removeItem: vi.fn(),
  clear: vi.fn(),
}
vi.stubGlobal('localStorage', localStorageMock)

// Mock sessionStorage
const sessionStorageMock = {
  getItem: vi.fn(),
  setItem: vi.fn(),
  removeItem: vi.fn(),
  clear: vi.fn(),
}
vi.stubGlobal('sessionStorage', sessionStorageMock)

// 抑制 console 警告（在测试环境中）
if (import.meta.env.NODE_ENV === 'test') {
  console.warn = vi.fn()
  console.error = vi.fn()
}